package cn.yjr.vector;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.yjr.vector.tools.MD5;
import cn.yjr.vector.tools.SharedPreferencesHelper;
import cn.yjr.vector.tools.YJRHttpClient;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

public class LoginActivity extends SherlockActivity implements OnClickListener{

	LayoutInflater inflater;
	ActionBar actionBar;
	EditText login_input_tel_et, login_input_key_et;
	ImageView login_user_imv, login_key_imv, input_tel_del_imv, input_key_del_imv;
	Button login_btn,register_now_btn;
	View title_bar;
	TextView forget_pwd_tv;
	Context context;
	String response;
	JSONObject jsonInfo;
	String phone, pwd;
	static final int LOGIN_MSG = 0;
	SharedPreferencesHelper spHelper;
	static String login_url = "http://115.28.222.1/yijiaren/user/login.action";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		inflater = this.getLayoutInflater();
		actionBar = getSupportActionBar();
		context = this;
		this.spHelper = new SharedPreferencesHelper(this.context);
		this.phone = this.spHelper.getStringValue("phone", "");
	    this.pwd = this.spHelper.getStringValue("password", "0");
	    Log.v("weiyi", phone+"  "+pwd);
	    if(!pwd.equals("0")){
	    	//这里不需要登录，因为即使登录了没有返回信息
	    	login(phone, pwd);
	    	//login_success();
	    }
		initTitleBar();
		
		initComponent();
		
		initEventListener();
		
		
		
	
	}
	
	private void initTitleBar(){
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.WRAP_CONTENT,Gravity.CENTER);
		title_bar = inflater.inflate(R.layout.login_action_bar, null);
		
		actionBar.setCustomView(title_bar,lp);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
	}
	private void initComponent(){
		login_input_tel_et = (EditText) findViewById(R.id.login_input_tel);
		login_input_key_et = (EditText) findViewById(R.id.login_input_key);
		
		this.login_input_tel_et.setText(this.phone);
		
		login_user_imv = (ImageView) findViewById(R.id.login_user_imv);
		login_key_imv = (ImageView) findViewById(R.id.login_key_imv);
		
		input_tel_del_imv = (ImageView) findViewById(R.id.input_tel_del);
		input_key_del_imv = (ImageView) findViewById(R.id.input_key_del);
		
		login_btn = (Button) findViewById(R.id.login_btn);
		
		forget_pwd_tv = (TextView) findViewById(R.id.forget_pwd);
		register_now_btn = (Button) findViewById(R.id.register_now);
		
		forget_pwd_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
	}
	
	private void initEventListener(){
		
		login_input_tel_et.addTextChangedListener(new TextWatcher(){
	
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
	
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if(s.length()==0){
					login_user_imv.setImageResource(R.drawable.login_user);
					input_tel_del_imv.setVisibility(View.INVISIBLE);
				}else{
					login_user_imv.setImageResource(R.drawable.login_user_hightlighted);
					input_tel_del_imv.setVisibility(View.VISIBLE);
				}
			}
	
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		
		login_input_key_et.addTextChangedListener(new TextWatcher(){
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
	
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if(s.length()==0){
					login_key_imv.setImageResource(R.drawable.login_key);
					input_key_del_imv.setVisibility(View.INVISIBLE);
				}else{
					login_key_imv.setImageResource(R.drawable.login_key_hightlighted);
					input_key_del_imv.setVisibility(View.VISIBLE);
				}
			}
	
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		input_key_del_imv.setOnClickListener(this);
		input_tel_del_imv.setOnClickListener(this);
		
		register_now_btn.setOnClickListener(this);
		forget_pwd_tv.setOnClickListener(this);
		login_btn.setOnClickListener(this);
		
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.input_tel_del:
			login_input_tel_et.setText("");
			input_tel_del_imv.setVisibility(View.INVISIBLE);
			break;
		case R.id.input_key_del:
			login_input_key_et.setText("");
			input_key_del_imv.setVisibility(View.INVISIBLE);
			break;
		case R.id.register_now:
			Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
			startActivity(intent);
			break;
		case R.id.forget_pwd:
			break;
		case R.id.login_btn:
			phone = login_input_tel_et.getText().toString();
			pwd = login_input_key_et.getText().toString();
			if(phone.isEmpty()||pwd.isEmpty()){
				Toast.makeText(context, "请输入手机号和密码", Toast.LENGTH_LONG).show();
			}else{
				login(phone, MD5.getMD5(pwd));
			}
			break;
		default:
				break;
		}
		
	}
	
	private void login(String phone, String pwd){
		final String phone_ = phone;
		final String pwd_ = pwd;
		RequestParams params = new RequestParams(); 
		params.add("phone", phone_);
        params.add("password", pwd_);
        Log.v("weiyi", phone_ +" " + pwd_);
		YJRHttpClient.post(context,"/user/login.action", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();
							YJRHttpClient.logCookie(context);
							spHelper.putString("phone", phone_);
							spHelper.putString("password", pwd_);
							login_success();
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
	
	private void login_success(){
		Intent intent = new Intent(LoginActivity.this, TabHomeActivity.class);
		startActivity(intent);
	}
	

}